import { Modal } from "antd";
import { useRef, useState, type PropsWithChildren } from "react";
import { useBlocker, type Location, useNavigate } from "react-router";

type NavigatePromptProps = PropsWithChildren<{
  shouldBlock: boolean;
}>;
export default function NavigatePrompt(props: NavigatePromptProps) {
  const { shouldBlock, children } = props;
  const [visible, setVisible] = useState(false);
  const confirmedRef = useRef(false); // 是否已确定转跳
  const navigate = useNavigate();
  const nextLocationRef = useRef<{
    location: Location;
    action: "POP" | "PUSH" | "REPLACE";
  } | null>(null);

  useBlocker(({ nextLocation, historyAction }) => {
    if (shouldBlock && !confirmedRef.current) {
      nextLocationRef.current = {
        location: nextLocation,
        action: historyAction,
      };
      setVisible(true);
      return true;
    }
    confirmedRef.current = false;
    return false;
  });

  function handleOk() {
    const { location, action } = nextLocationRef.current!;
    setVisible(false);
    confirmedRef.current = true;
    nextLocationRef.current = null;
    if (action === "POP") {
      navigate(-1);
    } else {
      navigate(
        {
          pathname: location.pathname,
          hash: location.hash,
          search: location.search,
        },
        { replace: action === "REPLACE" },
      );
    }
  }

  function handleReject() {
    setVisible(false);
    nextLocationRef.current = null;
  }

  return (
    <Modal
      open={visible}
      onOk={handleOk}
      onCancel={handleReject}
      onClose={handleReject}
    >
      {children}
    </Modal>
  );
}
